from django.core.cache import cache

from mongolog.models import StrategyLog


def calculate_deduction(weight, user_count, trigger_count):
    """
    计算安全扣分
    第i项策略的安全得分系数index = 1/2*1/(x+1) + 1/2*10/(10+y)，x为触发人数，y为触发次数
    扣分值=Wi*(1-index)，Wi为第i项安全策略的权重（或分值）
    """
    index = 1/2 * 1/(user_count+1) + 1/2 * 10/(trigger_count+10)
    return weight * (1 - index)


def trigger_count_serializer():
    """获取策略触发人数和次数"""
    cache_key = 'trigger_count_serializer'
    cache_data = cache.get(cache_key)
    if cache_data is None:
        queryset = StrategyLog.objects.mongo_aggregate([
            {
                '$group': {
                    '_id': '$uid',
                    'users': {'$addToSet': '$username'},
                    'trigger_count': {'$sum': 1}
                }
            },
            {
                '$project': {
                    'user_count': {'$size': '$users'},
                    'trigger_count': 1
                }
            }
        ])
        cache_data = {agg.pop('_id'): agg for agg in queryset}
        cache.set(cache_key, cache_data, timeout=60 * 10)
    return cache_data
